'use strict'

// 增加
function Insert() {
    window.location.href = `./addOrEdit.html`;
}

// 编辑
function Update(id) {
    window.location.href = `./addOrEdit.html?id=${id}`;
}

// 删除
function Delete(id) {
    $.ajax({
        url: `http://localhost:8080/blog/${id}`,
        type: 'DELETE',
        success: (res) => {
            alert(res);
            window.location.href = `./index.html`;
        }
    })
}

// 查找
function Query() {
    let keyword = $('[id = keyword]').val();
    let tb = $('table');
    tb.html(`
        <tr>
            <input type="text" placeholder="查找博客标题、摘要、内容、分类、作者" id="keyword">
            <input type="button" value="查找" onclick="Query()">
            <input type="button" value="新增" onclick="Insert()">
        </tr>
        <tr>
            <td>ID</td>
            <td>标题</td>
            <td>摘要</td>
            <td>内容</td>
            <td>分类</td>
            <td>作者</td>
            <td>发表时间</td>
            <td>操作</td>
        </tr>
    `)
    $.get(`http://localhost:8080/blog?keyword=${keyword}`, (res) => {
        res.forEach(item => {
            tb.append(`
                <tr>
                    <td>${item.id}</td>
                    <td>${item.title}</td>
                    <td>${item.digest}</td>
                    <td>${item.text}</td>
                    <td>${item.classify}</td>
                    <td>${item.author}</td>
                    <td>${item.updatedAt}</td>
                    <td>
                        <input type="button" value="修改" onclick="Update(${item.id})">
                        <input type="button" value="删除" onclick="Delete(${item.id})">
                    </td>
                </tr>
            `)
        });
    });
}

// 保存
function Save() {
    let id = window.location.search.split('=')[1] || '';
    let obj = {
        title: $('[id = title]').val(),
        digest: $('[id = digest]').val(),
        text: $('[id = text]').val(),
        classify: $('[id = classify]').val(),
        author: $('[id = author]').val(),
    }
    if (id) {
        $.ajax({
            url: `http://localhost:8080/blog/${id}`,
            type: 'PUT',
            data: obj,
            success: (res) => {
                alert(res);
                window.location.href = `./index.html`;
            }
        })
    } else {
        $.post(`http://localhost:8080/blog`, obj, (res) => {
            alert(res);
            window.location.href = `./index.html`;
        })
    }
}

//返回
function Back() {
    window.location.href = `./index.html`;
}